<template>
  <el-container class="main_con proAdd">
    <div class="list_con nomt nopt" style="padding-bottom:0;">
      <el-form label-width="100px" size="medium">
        <el-form-item label="配送方式">
          <el-checkbox-group v-model="form.type">
            <el-checkbox label="1">商家配送</el-checkbox>
            <el-checkbox label="2">第三方</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="第三方配置" v-if="form.type.indexOf('2') > -1">
          <el-checkbox-group v-model="form.third_party">
            <div class="card_div">
              <el-tabs type="border-card">
                <el-tab-pane v-for="(item, i) in form.config" :disabled="i == 1">
                  <span slot="label" class="card_label">
                    <el-checkbox :disabled="i == 1" :label="item.id" :value="item.id"></el-checkbox>
                    {{ item.name }}
                  </span>
                  <el-form-item label="key"><el-input v-model="item.app_key"></el-input></el-form-item>
                  <el-form-item label="secret"><el-input v-model="item.app_secret"></el-input></el-form-item>
                  <el-form-item label="商户编号"><el-input v-model="item.app_source_id"></el-input></el-form-item>
                  <el-form-item label="门店编号"><el-input v-model="item.app_store_number"></el-input></el-form-item>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="门店地址"><el-input v-model="form.shop_address" disabled></el-input></el-form-item>
        <el-form-item label="配送区域">
          <el-radio-group v-model="form.area">
            <el-radio :label="1">按不同区域</el-radio>
            <el-radio :label="2">按不同距离</el-radio>
            <el-radio :label="3">按行政区域</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="划分方式" v-if="form.area != 3">
          <el-radio-group @change="chengetype" v-model="form.divide_type">
            <el-radio :label="1">按半径</el-radio>
            <el-radio :label="2">自定义</el-radio>
          </el-radio-group>
          <div class="flex_div">
            <div class="flex_left">
              <div class="list">
                <div class="item" v-bind:class="item.editable ? 'active' : ''" @click="ChangeEidt(index)" v-for="(item, index) in form.divide_config">
                  <div class="item_top">
                    <span>区域{{ index + 1 }}</span>
                    <el-button type="text" @click="del(index)">删除</el-button>
                  </div>
                  <el-form-item label="起送金额">
                    <el-input v-model="item.starting_amount">
                      <template slot="prepend">
                        起
                      </template>
                      <template slot="append">
                        元
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="配送费" v-if="form.area == 1"><el-input v-model="item.distribution_fee"></el-input></el-form-item>
                  <el-form-item label="半径" v-if="form.divide_type == 1">
                    <!-- <el-input v-model="item.radius"></el-input> -->
                    <Linput @change="changeradius($event, index)" :radius="item.d_radius"></Linput>
                  </el-form-item>
                  <el-form-item label="免配送费">
                    <el-radio-group v-model="item.is_distribution">
                      <el-radio :label="1">是</el-radio>
                      <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item v-if="item.is_distribution == 1" label="免额条件">
                    <el-input v-model="item.commodity.money">
                      <template slot="prepend">
                        满
                      </template>
                      <template slot="append">
                        元
                      </template>
                    </el-input>
                  </el-form-item>
                </div>
              </div>
              <div @click="addconfig" class="addbtn">
                <el-button :disabled="form.divide_config.length > 9" type="text">新增区域({{ form.divide_config.length }}/10)</el-button>
              </div>
            </div>
            <div class="map_area">
              <amap :zoom="12" :center="position" @click="mapClick">
                <amap-circle
                  v-if="showtype == 1"
                  v-for="(item, index) in form.divide_config"
                  :center.sync="item.center"
                  :radius.sync="item.d_radius"
                  :editable="item.editable"
                  :fill-color="fill"
                  :fill-opacity="0.5"
                  :strokeColor="stroke"
                  :draggable="draggable"
                  :cursor="draggable ? 'pointer' : 'default'"
                  @click="ChangeEidt(index)"
                />
                <amap-polygon @click="ChangeEidt(index)" :editable="item.editable" v-if="showtype == 2" :path.sync="item.data" v-for="(item, index) in form.divide_config" />
                <amap-marker :position="position"></amap-marker>
                <amap-tool-bar />
                <amap-scale />
              </amap>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="计费方式" v-if="form.area == 2">
          <div class="input_div">
            <span class="span">配送距离</span>
            <el-input-number class="input_km" size="mini" :controls="false" v-model="form.billing_method.distance"></el-input-number>
            <span class="span">内，配送费用</span>
            <el-input-number size="mini" class="input_cos" :controls="false" v-model="form.billing_method.distribution_costs"></el-input-number>
          </div>
          <div class="input_div">
            <span class="span">配送距离每增加</span>
            <el-input-number class="input_km" size="mini" :controls="false" v-model="form.billing_method.second_distance"></el-input-number>
            <span class="span">运费将增加</span>
            <el-input-number class="input_cos" size="mini" :controls="false" v-model="form.billing_method.second_freight"></el-input-number>
          </div>
          <div class="input_div">
            <span class="span">超出</span>
            <el-input-number class="input_km" size="mini" :controls="false" v-model="form.billing_method.over_distance"></el-input-number>
            <span class="span">固定运费</span>
            <el-input-number class="input_cos" size="mini" :controls="false" v-model="form.billing_method.over_freight"></el-input-number>
          </div>
        </el-form-item>
        <el-form-item label="续重收费" v-if="form.area != 3">
          <div class="input_div">
            <span>商品重量</span>
            <el-input-number class="input_kg" size="mini" :controls="false" v-model="form.renewal_charge.weight"></el-input-number>
            <span>内不额外收费，每超出</span>
            <el-input-number class="input_kg" size="mini" :controls="false" v-model="form.renewal_charge.continuation"></el-input-number>
            <span>费用增加</span>
            <el-input-number class="input_cos" size="mini" :controls="false" v-model="form.renewal_charge.money"></el-input-number>
          </div>
        </el-form-item>

        <el-form-item v-if="form.area == 3" label="行政区域">
          <el-select v-model="form.area_data" multiple>
            <el-option v-for="(item, i) in arealist" :key="item.area_code" :label="item.name" :value="item.area_code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起送金额" v-if="form.area == 3"><el-input v-model="form.area_config.starting_amount"></el-input></el-form-item>
        <el-form-item label="配送费" v-if="form.area == 3"><el-input v-model="form.area_config.money"></el-input></el-form-item>
        <el-form-item label="高德地图key"><el-input v-model="form.gaude_key"></el-input></el-form-item>
        <!--    <el-form-item label="是否使用快递">
          <el-radio-group v-model="form.is_range">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item><el-button type="primary" @click="save">保存</el-button></el-form-item>
      </el-form>
    </div>
  </el-container>
</template>

<script>
import {loadAmap, loadPlugins} from '@amap/amap-vue';
import AMap from '@/components/AMap/index';
import {getStore} from '@/api/shop/store';
import {getdistribution, savedistribution, getJurisdiction} from '@/api/shop/distribution';
import Linput from './components/Linput.vue';
import {getLonAndLat} from '@/utils/index';
export default {
  data() {
    return {
      center: [120.670565, 28.001373],
      radius: 1000,
      fill: '#ff0000',
      stroke: '#000A58',
      editable: true,
      draggable: true,
      position: [120.670565, 28.001373],
      radius: 1000,
      del_type: [],
      store_id: '',
      showtype: 1,
      arealist: [],
      form: {
        gaude_key: '',
        type: ['1'],
        third_party: [], //	否	string	第三方配送，1-美团配送 2-达达配送，用，拼接
        config: [
          {
            name: '达达',
            id: 2,
            app_key: '', //	否	string	第三方配送配置信息-第三方key
            app_secret: '', //否	string	第三方配送配置信息-第三方secret
            app_source_id: '', //	否	string	第三方配送配置信息-第三方商户编号
            app_store_number: '' //	否	string	第三方配送配置信息-第三方门店编号
          },
          {
            name: '美团',
            id: 1,
            app_key: '', //	否	string	第三方配送配置信息-第三方key
            app_secret: '', //否	string	第三方配送配置信息-第三方secret
            app_source_id: '', //	否	string	第三方配送配置信息-第三方商户编号
            app_store_number: '' //	否	string	第三方配送配置信息-第三方门店编号
          }
        ],
        shop_address: '',
        area: 1,
        divide_type: 1,
        area_data: [],
        gaude_key: '',
        divide_config: [],
        billing_method: {
          distance: 0,
          distribution_costs: 0,
          second_distance: 1,
          second_freight: 0,
          over_distance: 0,
          over_freight: 0
        },
        renewal_charge: {
          weight: 0,
          continuation: 0,
          money: 0
        },
        area_config: {
          starting_amount: 0,
          money: 0
        },
        is_range: 0
      },
      storelist: [],
      circlelist: [
        {
          color: '',
          editable: false
        }
      ]
    };
  },
  created() {
    if (this.$route.query.id) {
      this.store_id = this.$route.query.id;
      this.getdetail();
    }
  },

  methods: {
    del(i) {
      this.form.divide_config.splice(i, 1);
    },
    getJurisdiction(address) {
      let data = {
        address: address
      };
      getJurisdiction(data).then(res => {
        let arealist = res.msg;
        arealist.forEach(a => {
          a.area_code = '' + a.area_code;
        });
        this.arealist = arealist;
      });
    },
    chengetype(e) {
      if (e == 2) {
        this.form.divide_config = [];
        this.getpl();
      } else {
        this.form.divide_config = [];
        this.init(this.position);
      }
    },
    changeradius(e, i) {
      this.form.divide_config[i].d_radius = e * 1000;
      this.form.divide_config[i].radius = e;
    },
    //保存
    save() {
      this.form.divide_config.forEach(a => {
        a.dot.latitude = a.center[1];
        a.dot.longitude = a.center[0];
      });
      let data = {
        store_id: this.store_id,
        type: this.form.type.join(','),
        third_party: this.form.third_party.join(','), //	否	string	第三方配送，1-美团配送 2-达达配送，用，拼接
        config: JSON.stringify(this.form.config),
        shop_address: this.form.shop_address,
        area: this.form.area,
        divide_type: this.form.divide_type,
        area_data: this.form.area_data.join(','),
        gaude_key: this.form.gaude_key,
        divide_config: JSON.stringify(this.form.divide_config),
        billing_method: JSON.stringify(this.form.billing_method),
        renewal_charge: JSON.stringify(this.form.renewal_charge),
        area_config: JSON.stringify(this.form.area_config),
        is_range: this.form.is_range
      };
      savedistribution(data).then(res => {
        this.$router.push({path: '/distribution/list'});
      });
    },
    //获取详情
    getdetail() {
      let data = {
        store_id: this.store_id
      };
      console.log(1);
      getdistribution(data).then(res => {
        let data = res.msg;
        if (data) {
          this.form.type = data.type.split(',');
          let third_party = data.third_party.split(','); //	否	string	第三方配送，1-美团配送 2-达达配送，用，拼接
          let list = [];
          third_party.forEach(a => {
            if (a) {
              list.push(Number(a));
            }
          });
          this.form.third_party = list;
          this.form.config = JSON.parse(data.config);
          // shop_address:data.shop_address,
          this.form.area = data.area;
          this.form.divide_type = data.divide_type;
          this.form.area_data = data.area_data ? data.area_data.split(',') : [];
          this.form.gaude_key = data.gaude_key;
          this.form.divide_config = JSON.parse(data.divide_config);
          this.form.billing_method = JSON.parse(data.billing_method);
          this.form.renewal_charge = JSON.parse(data.renewal_charge);
          this.form.is_range = data.is_range;
          this.form.area_config = data.area_config ? JSON.parse(data.area_config) : {starting_amount: 0, money: 0};
          this.showtype = data.divide_type;
          console.log(this.form);
        }

        this.getStoreData();
      });
    },
    addconfig() {
      if (this.showtype == 1) {
        this.init(this.position);
      } else {
        this.getpl();
      }
    },
    ChangeEidt(i) {
      this.form.divide_config.forEach(a => {
        a.editable = false;
      });
      this.form.divide_config[i].editable = true;
    },
    init(position, data) {
      this.form.divide_config.push({
        starting_amount: 0,
        distribution_fee: 0,
        d_radius: 2000,
        raduis: 2,
        is_distribution: 0,
        commodity: {
          money: 0
        },
        editable: false,
        dot: {
          longitude: position[0],
          latitude: position[1]
        },
        center: [position[0], position[1]],
        data: data || []
      });
      if (data) {
        this.showtype = 2;
      } else {
        this.showtype = 1;
      }
    },
    getpl() {
      let data = [];
      for (var i = 0; i < 4; i++) {
        if (i == 0) {
          let a = this.position[0] - 0.02;
          let b = this.position[1] + 0.02;
          data.push([a, b]);
        }
        if (i == 1) {
          let a = this.position[0] + 0.02;
          let b = this.position[1] + 0.02;
          data.push([a, b]);
        }
        if (i == 2) {
          let a = this.position[0] + 0.02;
          let b = this.position[1] - 0.02;
          data.push([a, b]);
        }
        if (i == 3) {
          let a = this.position[0] - 0.02;
          let b = this.position[1] - 0.02;
          data.push([a, b]);
        }
      }
      this.init(this.position, data);
      // this.form.divide_config[0].data = data;
      // console.log(this.form.divide_config[0].data);
    },
    mapClick() {},
    //获取编辑页面基础数据
    getStoreData() {
      getStore(this.store_id).then(res => {
        let o = res.msg;
        this.form.shop_address = o.district.replace(/,/g, '') + o.address;

        this.position = [o.longitude, o.latitude];
        // this.getpl();
        if (this.form.divide_config.length == 0) {
          this.form.divide_config.push({
            starting_amount: 0,
            distribution_fee: 0,
            d_radius: 2000,
            raduis: 2,
            is_distribution: 0,
            commodity: {
              money: 0
            },
            editable: false,
            dot: {
              longitude: o.longitude,
              latitude: o.latitude
            },
            center: [o.longitude, o.latitude],
            data: []
          });
        }

        this.$ready = new Promise(async resolve => {
          const AMap = await loadAmap();
          await loadPlugins(['AMap.PlaceSearch', 'AMap.AutoComplete']);
          this.ac = new AMap.AutoComplete();
          resolve();
        });
        this.getJurisdiction(o.district);
      });
    }
  },
  components: {
    AMap,
    Linput
  }
};
</script>
<style type="text/css">
.card_label .el-checkbox__label {
  opacity: 0 !important;
  padding: 0;
}
</style>
<style lang="scss" scoped>
.el-input {
  width: 400px;
}

.flex_div {
  display: flex;
  height: 500px;
  .flex_left {
    width: 330px;
    height: 500px;
    margin-right: 20px;
    .list {
      overflow-y: scroll;
      height: 480px;
      .item {
        cursor: pointer;
        border: 1px solid #e9edef;
        &.active {
          border: 1px solid #007aff;
        }
        .item_top {
          background-color: #f8f8f8;
          padding: 0 15px;
          margin-bottom: 15px;
          display: flex;
          justify-content: space-between;
        }
      }
    }
    .el-input {
      width: 200px;
    }
  }
  .map_area {
    flex: 1;
    height: 500px;
  }
}
.input_div {
  .span {
    display: inline-block;
    width: 110px;
  }
  .input_km {
    margin-right: 10px;
    &.el-input-number {
      &::after {
        content: 'km';
        position: absolute;
        right: 10px;
        top: 0px;
      }
    }
  }
  .input_kg {
    margin: 0 10px;
    &.el-input-number {
      &::after {
        content: 'kg';
        position: absolute;
        right: 10px;
        top: 0px;
      }
    }
  }
  .input_cos {
    &.el-input-number {
      &::after {
        content: '元';
        position: absolute;
        right: 10px;
        top: 0px;
      }
    }
  }
  .el-input-number {
    width: 80px;
    position: relative;

    .el-input {
      width: 80px;
    }
  }
}
.card_div {
  width: 600px;
}
.addbtn {
  text-align: center;
}
</style>
